package com.xtjc.recsyslog.netty.util;

import com.xtjc.recsyslog.netty.entity.ChargeEntity;
import io.netty.channel.Channel;
import io.netty.util.Attribute;
import io.netty.util.AttributeKey;

import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.CopyOnWriteArrayList;

public class NettyUtil {

    public static final AttributeKey<ChargeEntity> NETTY_CHANNEL_KEY = AttributeKey.valueOf("netty.channel");
    private static final ConcurrentHashMap<Long, CopyOnWriteArrayList<Channel>> ONLINE_SN_MAP = new ConcurrentHashMap<>();
    public static AttributeKey<String> SN = AttributeKey.valueOf("sn");
    //保存所有充电桩回话
    public static ConcurrentHashMap<String, ChargeEntity> channelMap = new ConcurrentHashMap<>();

    public static <T> void setAttr(Channel channel, AttributeKey<T> attributeKey, T data) {
        Attribute<T> attr = channel.attr(attributeKey);
        attr.set(data);
    }

    public static <T> T getAttr(Channel channel, AttributeKey<T> ip) {
        return channel.attr(ip).get();
    }

    public static void putChannel(String key, ChargeEntity charge) {
        if (channelMap.containsKey(key)) {
            return;
        }
        setAttr(charge.getChannel(),NETTY_CHANNEL_KEY,charge);
        channelMap.put(key, charge);
    }

    public static void removeChannel(String key){
        channelMap.remove(key);
    }

    public static ChargeEntity getChannel(String key) {
        return channelMap.get(key);
    }

    public static String[] getChannelNames() {
        return channelMap.keySet().toArray(new String[0]);
    }
}
